<?php


namespace App\Services\Game;


use App\DTOS\NeiGouDTO;
use App\Exceptions\ServiceException;
use App\Models\Game\Server;
use App\Utils\MyLog;
use Illuminate\Support\Facades\Http;


/** 内购
 * Class NeigouService
 * @package App\Services\Game
 */
class NeigouService
{

    /**
     * @param NeiGouDTO $NeiGouDTO
     * @return bool
     * @throws ServiceException
     */
    public function pushToServer(NeiGouDTO $NeiGouDTO)
    {

        $row = Server::query()->where('can_push',1)->where("server_id",$NeiGouDTO->getGameArea())->first();
        $pushUrl = data_get($row,'push_url');
        MyLog::info("传入的加赠比例是否".json_encode($NeiGouDTO->getDiscount()));
        $requestBody = [
            "RoleId"=>$NeiGouDTO->getRoleId(),
            "GoodsId"=>$NeiGouDTO->getGoodsId(),
            "Amount"=>$NeiGouDTO->getNumber(),
            "OrderNum"=>$NeiGouDTO->getOrderNo(),
            'TypeValue'=>$NeiGouDTO->getTypeValue(),
            'discount'=>$NeiGouDTO->getDiscount() ?? 0,
            'Sign'=>"",
            "Kind"=>0,
            'Virtual'=>1,
            'platform'=>"android"
        ];
        MyLog::info('推送消息体'.json_encode($requestBody));
        MyLog::info('推送地址'.json_encode($pushUrl));
        $response = Http::withHeaders(['Content-Type'=>'application/json'])
            ->post($pushUrl.'/Api/Iap/DeliverGoods',$requestBody);
        //Log::info("push to server response:" . $response);

        $body = json_decode($response->body(),true);
        $RetCode = data_get($body,'RetCode');
        MyLog::info('推送结果'.json_encode($body));
        if ($RetCode == 0){
            return true;
        }
        switch($RetCode) {
            case 1: throw new ServiceException("失败");
            case 3: throw new ServiceException("未找到角色");
            case 4: throw new ServiceException("操作正在处理");
            case 1000: throw new ServiceException("无效JSON参数");
            case 2000: throw new ServiceException("商品未找到");
        }
    }

}
